package cn.edu.zhku.citrusmonitor.person.admin.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import cn.edu.zhku.citrusmonitor.domain.TbAdmin;
import cn.edu.zhku.citrusmonitor.person.admin.service.AdminService;
import cn.edu.zhku.citrusmonitor.person.admin.service.AdminServiceImpl;
import cn.edu.zhku.citrusmonitor.person.util.Message;
import cn.edu.zhku.citrusmonitor.person.util.RandomColor;
import cn.edu.zhku.citrusmonitor.util.BaseServlet;

@WebServlet("/admin.do")
public class AdminServlet extends BaseServlet {
	
	private static final long serialVersionUID = 1L;
	AdminService as=new AdminServiceImpl();
	public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String[]> m=new HashMap<String,String[]>();
		m=request.getParameterMap();
		TbAdmin admin=new TbAdmin();
		//System.out.print(request.getSession().getAttribute("checkedCode"));
		if(request.getSession().getAttribute("checkedCode").equals(m.get("checkedCode")[0])) {
			String adminAccount=m.get("adminAccount")[0];
			String password=m.get("adminAccount")[0];
			if(as.searchByadminAccount(adminAccount)!=null) {
				if((admin=as.login(adminAccount,password))!=null) {
					//用户放入session当中 
					System.out.print(JSON.toJSONString(new Message("1","登陆成功")));
					request.getSession().setAttribute("admin",admin);               //放入session当中，以便于修改信息时取出id
					//System.out.println((TbUser)request.getSession().getAttribute("user"));
					//request.getRequestDispatcher("/modify.html").forward(request, response);;
					return JSON.toJSONString(new Message("1","登陆成功",admin.getAdminAccount()));
				}else
					return JSON.toJSONString(new Message("2","用户名或密码错误"));
			}else
				System.out.print(JSON.toJSONString(new Message("2","此用户不存在")));
				return JSON.toJSONString(new Message("2","此用户不存在"));
		}else {
			//JSONObject.fromObject(object);
			System.out.print(JSON.toJSONString(new Message("2","验证码错误")));
			return JSON.toJSONString(new Message("2","验证码错误")); 
		}
	}
	/**
	 * 获得验证码图片
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void checkImg(HttpServletRequest request,HttpServletResponse response) throws IOException {
		if(request.getSession().getAttribute("words")==null) {     //判断是否第一次进入此页面
			List<String> words=new ArrayList<>();
			String path=request.getServletContext().getRealPath("/WEB-INF/new_words.txt");//获取验证码文字
			//读取每一行文字
			BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(path),"UTF-8"));
			String line;
			while((line=br.readLine())!=null) {
				words.add(line);
			}
			//存入session中
//			System.out.print("a"+words.get(1));
			request.getSession().setAttribute("words", words);
		}
		
		//draw a picture in 120 width,30 height
		List<String> words=(List<String>)request.getSession().getAttribute("words");
//		System.out.print("0out"+words.get(1));
		int width=120;
		int height=30;
		BufferedImage img=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics graphics=img.getGraphics();
		//get random color from 100 to 180
		graphics.setColor(RandomColor.getRandColor(200, 250));
		//fill its background-color
		graphics.fillRect(0, 0, width, height);
		graphics.setColor(Color.white);
		//draw its rect
		graphics.drawRect(0, 0, width-1, height-1);
		Graphics2D graphics2d=(Graphics2D)graphics;
		graphics2d.setFont(new Font("宋体", Font.BOLD, 18));
		Random random=new Random();
		String word=words.get(random.nextInt(words.size()));
		int x=10;
		//write words
		for(int i=0;i<word.length();i++) {
			//a random color of a word
			graphics2d.setColor(RandomColor.getRandColor(80, 150));
			int angle=random.nextInt(60)-30;
			double theta= angle*Math.PI/180;
			graphics2d.rotate(theta,x,20);
			char c=word.charAt(i);
			graphics2d.drawString(String.valueOf(c), x, 20);
			graphics2d.rotate(-theta,x,20);
			x+=30;
		}
		request.getSession().setAttribute("checkedCode", word);
		//add disturbing string
		graphics2d.setColor(RandomColor.getRandColor(120, 180));
		for(int i=0;i<30;i++) {
			int x1=random.nextInt(width);
			int y1=random.nextInt(height);
			int x2=random.nextInt(12);
			int y2=random.nextInt(12);
			graphics2d.drawLine(x1, y1, x1+x2, x2+y2);
		}	
		graphics2d.dispose();
		graphics.dispose();
		ImageIO.write(img, "jpg",response.getOutputStream());
	}
	
}
